const lodash = require('lodash')
const Base = require('@/entities/Base')
import path from 'path'
import fsExtra from 'fs-extra'
import { app } from 'electron'
import { funcFns } from '@/puppeteer/utils/funtion'
import { dictToWhere } from '@/utils/sqlUtils'

const ArticleDao = {
  table: 'data',
  pageSize: Base.pageSize,
}

ArticleDao.initialForm = () => {
  return JSON.parse(
    JSON.stringify({
      id: 0,
      title: '',
      link: '',
      status: 0,
      sourceId: 0,
      platformId: 0,
      content: '',
      aiResult: '',
    })
  )
}

ArticleDao.content = (article) => {
  console.log('articleDao', article)
  let content = article.content
  if (typeof content == 'string') {
    content = JSON.parse(content)
  }
  return funcFns.deepTraversal(content)
}

ArticleDao.fetchAll = async (whereDict) => {
  let whereSql = dictToWhere(whereDict)
  return await Base.fetchAll(ArticleDao.table, whereSql)
}

ArticleDao.fetchOne = async (whereDict) => {
  let whereSql = dictToWhere(whereDict)
  return await Base.fetchOne(ArticleDao.table, whereSql)
}

ArticleDao.fetchPage = async (whereDict, page, pageSize) => {
  if (!pageSize) {
    pageSize = ArticleDao.pageSize
  }
  let whereSql = dictToWhere(whereDict)
  console.log('fetchPage', whereSql, 'page', page)
  return await Base.fetchPage(ArticleDao.table, whereSql, page, pageSize)
}

ArticleDao.fetchCount = async (whereDict, page, pageSize) => {
  let count = await ArticleDao.countWhere(whereDict)
  let datas = await ArticleDao.fetchPage(whereDict, page, pageSize)
  return { count, datas }
}

ArticleDao.countWhere = async (whereDict) => {
  let whereSql = dictToWhere(whereDict)
  return await Base.countWhere(ArticleDao.table, whereSql)
}

ArticleDao.save = async (obj) => {
  let article = await ArticleDao.fetchOne({ link: obj.link })
  if (!lodash.isEmpty(article)) {
    obj.id = article.id
  }
  if (typeof obj.content != 'string') {
    obj.content = JSON.stringify(obj.content)
  }
  if (lodash.isEmpty(obj.aiResult)) {
    obj.aiResult = ''
  }
  if (typeof obj.aiResult != 'string') {
    obj.aiResult = JSON.stringify(obj.aiResult)
  }
  return await Base.save(ArticleDao.table, obj)
}

ArticleDao.delete = async (id) => {
  return await Base.delete(ArticleDao.table, id)
}

ArticleDao.folderPath = (row) => {
  let basePath = app.getPath('userData')
  let folderPath = path.join(basePath, String(row.platformId), funcFns.calculateMD5(row.link))
  if (!fsExtra.pathExistsSync(folderPath)) {
    fsExtra.mkdirSync(folderPath, { recursive: true })
  }
  return folderPath
}

ArticleDao.getMediaFiles = (row) => {
  let folderPath = ArticleDao.folderPath(row)
  return funcFns.getFiles(folderPath)
}

export { ArticleDao }
